import { getAuthInfo } from './erpapi';
import { getCurrentChatId, getChatTitle } from './whatsappHandler';
import { STORAGE_KEYS } from './defines';

// 消息数据接口
interface MessageData {
    message_id: string;
    is_me: boolean;
    is_group: boolean;
    message_from: string;
    message_to: string;
    timestamp: number;
    message_from_name: string;
    body: string;
}

// 存储最近同步的时间戳
const lastSyncTimestamps: Record<string, number> = {};
// 同步冷却时间（毫秒）
const SYNC_COOLDOWN = 5000; // 5秒冷却时间
// 正在同步的聊天ID集合
const syncingChats = new Set<string>();

/**
 * 创建一个防抖函数
 * @param func 要执行的函数
 * @param wait 等待时间
 */
export function debounce<T extends (...args: any[]) => any>(func: T, wait: number): (...args: Parameters<T>) => void {
    let timeout: number | null = null;
    
    return function(...args: Parameters<T>): void {
        const later = () => {
            timeout = null;
            func(...args);
        };
        
        if (timeout !== null) {
            clearTimeout(timeout);
        }
        timeout = window.setTimeout(later, wait) as unknown as number;
    };
}

/**
 * 获取当前聊天的所有消息
 * @returns 消息数据数组
 */
export async function fetchCurrentChatMessages(): Promise<MessageData[]> {
    const messageRows = document.querySelectorAll('#main div[role="row"]');
    const messagesData: MessageData[] = [];
    
    // 获取当前账号ID
    const myAccount = await getStoredAccountID();
    
    messageRows.forEach(row => {
        // 获取消息的容器
        const messageDiv = row.querySelector('div[data-id]');
        if (!messageDiv) return;

        const dataId = messageDiv.getAttribute('data-id');
        if (!dataId) return;

        // 解析 data-id: isFromMe_remoteJid_messageId_participantJid(optional)
        const parts = dataId.split('_');
        if (parts.length < 3) return;

        const [isFromMe, remoteJid, msgId, participantJid] = parts;

        // 检查必要字段
        if (!remoteJid || !msgId) return;

        // 检查是否是群聊
        const isGroup = remoteJid.endsWith('@g.us');

        // 确定消息发送者和接收者
        let messageFrom = '';
        let messageTo = '';
        if (isFromMe === 'true') {
            // 我发送的消息
            messageFrom = myAccount;
            messageTo = participantJid || remoteJid;
        } else {
            // 别人发送的消息
            if (isGroup && participantJid) {
                // 群聊中别人的消息
                messageFrom = participantJid;
                messageTo = myAccount;
            } else {
                // 私聊中别人的消息
                messageFrom = remoteJid;
                messageTo = myAccount;
            }
        }

        // 获取消息时间和发送者信息
        const prePlainDiv = row.querySelector('div[data-pre-plain-text]');
        if (!prePlainDiv) return;

        const prePlainText = prePlainDiv.getAttribute('data-pre-plain-text') || '';
        const match = prePlainText.match(/\[(.*?)\]\s*(.*?):/);
        if (!match) return;

        const timeInfo = match[1].trim();
        const senderName = match[2].trim();

        // 解析时间戳
        const timestamp = parseMessageTimestamp(timeInfo);
        if (!timestamp) {
            console.warn(`无法解析时间信息: ${timeInfo}`);
            return;
        }

        // 获取消息内容
        const textContainer = row.querySelector('span.selectable-text.copyable-text');
        if (!textContainer) return;

        const textContent = textContainer.textContent?.trim() || '';
        if (!textContent) return;

        // 添加消息数据
        messagesData.push({
            message_id: msgId,
            is_me: isFromMe === 'true',
            is_group: isGroup,
            message_from: messageFrom,
            message_to: messageTo,
            timestamp: timestamp,
            message_from_name: senderName,
            body: textContent
        });
    });

    return messagesData;
}

/**
 * 解析消息时间戳
 * @param timeInfo 时间信息字符串
 * @returns 时间戳（毫秒）
 */
function parseMessageTimestamp(timeInfo: string): number | null {
    const patterns = [
        {
            // 中文格式: "17:50, 2024年12月6日"
            regex: /(\d{1,2}):(\d{2}),\s*(\d{4})年(\d{1,2})月(\d{1,2})日/,
            parser: (match: RegExpMatchArray) => ({
                hour: parseInt(match[1], 10),
                minute: parseInt(match[2], 10),
                year: parseInt(match[3], 10),
                month: parseInt(match[4], 10) - 1,
                day: parseInt(match[5], 10)
            })
        },
        {
            // 英文格式: "17:50, 12/6/2024" or "17:50, 12-6-2024"
            regex: /(\d{1,2}):(\d{2}),\s*(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,
            parser: (match: RegExpMatchArray) => ({
                hour: parseInt(match[1], 10),
                minute: parseInt(match[2], 10),
                month: parseInt(match[3], 10) - 1,
                day: parseInt(match[4], 10),
                year: parseInt(match[5], 10)
            })
        },
        {
            // ISO格式: "17:50, 2024-12-06"
            regex: /(\d{1,2}):(\d{2}),\s*(\d{4})-(\d{1,2})-(\d{1,2})/,
            parser: (match: RegExpMatchArray) => ({
                hour: parseInt(match[1], 10),
                minute: parseInt(match[2], 10),
                year: parseInt(match[3], 10),
                month: parseInt(match[4], 10) - 1,
                day: parseInt(match[5], 10)
            })
        },
        {
            // 带am/pm的格式: "3:46 pm, 27/02/2025"
            regex: /(\d{1,2}):(\d{2})\s*([ap]m),\s*(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/i,
            parser: (match: RegExpMatchArray) => {
                let hour = parseInt(match[1], 10);
                const isPM = match[3].toLowerCase() === 'pm';

                // 处理12小时制转换
                if (isPM && hour < 12) hour += 12;
                if (!isPM && hour === 12) hour = 0;

                return {
                    hour: hour,
                    minute: parseInt(match[2], 10),
                    day: parseInt(match[4], 10),
                    month: parseInt(match[5], 10) - 1,
                    year: parseInt(match[6], 10)
                };
            }
        }
    ];

    for (const pattern of patterns) {
        const match = timeInfo.match(pattern.regex);
        if (match) {
            const { hour, minute, year, month, day } = pattern.parser(match);
            const date = new Date(year, month, day, hour, minute);

            if (!isNaN(date.getTime())) {
                return date.getTime();
            }
        }
    }

    return null;
}

/**
 * 获取存储的账号ID
 * @returns 账号ID
 */
export async function getStoredAccountID(): Promise<string> {
    return new Promise((resolve) => {
        chrome.storage.local.get([STORAGE_KEYS.ACCOUNT_ID], (result) => {
            resolve(result[STORAGE_KEYS.ACCOUNT_ID] || '');
        });
    });
}

/**
 * 获取存储的消息数量
 * @param chatId 聊天ID
 * @returns 消息数量
 */
export async function getStoredMessageCount(chatId: string): Promise<number> {
    return new Promise((resolve) => {
        chrome.storage.local.get([STORAGE_KEYS.MESSAGE_COUNTS], (result) => {
            const counts = result[STORAGE_KEYS.MESSAGE_COUNTS] || {};
            resolve(counts[chatId] || 0);
        });
    });
}

/**
 * 更新存储的消息数量
 * @param chatId 聊天ID
 * @param count 消息数量
 */
export async function updateStoredMessageCount(chatId: string, count: number): Promise<void> {
    return new Promise((resolve, reject) => {
        chrome.storage.local.get([STORAGE_KEYS.MESSAGE_COUNTS], (result) => {
            const counts = result[STORAGE_KEYS.MESSAGE_COUNTS] || {};
            counts[chatId] = count;
            
            chrome.storage.local.set({
                [STORAGE_KEYS.MESSAGE_COUNTS]: counts
            }, () => {
                if (chrome.runtime.lastError) {
                    reject(chrome.runtime.lastError);
                } else {
                    resolve();
                }
            });
        });
    });
}

/**
 * 发送消息到ERP后台
 * @param chatId 聊天ID
 * @param messagesData 消息数据
 * @returns 是否成功
 */
export async function sendMessagesToERP(chatId: string, messagesData: MessageData[]): Promise<boolean> {
    try {
        const authInfo = await getAuthInfo();
        if (!authInfo.authorization || !authInfo.ptoken) {
            console.error('缺少认证信息，无法发送消息到 ERP');
            return false;
        }
        
        const accountId = await getStoredAccountID();
        const nickname = getChatTitle();
        
        // 获取头像
        const avatar = getHeaderImage();
        
        // 构造要发送的数据
        const payload = {
            chat_serialized: chatId,
            nickname: nickname,
            avatar: avatar,
            account_serialized: accountId,
            messages: messagesData.map(msg => {
                return {
                    id_message: msg.message_id,
                    is_me: msg.is_me,
                    is_group: msg.is_group,
                    message_from: msg.message_from,
                    message_to: msg.message_to,
                    timestamp: msg.timestamp,
                    message_from_name: msg.message_from_name,
                    body: msg.body
                };
            })
        };

        // 发送请求到 ERP 后台
        const response = await fetch('https://tools.kikimami.com/crm/api/syncwam/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authInfo.authorization,
                'ptoken': authInfo.ptoken
            },
            body: JSON.stringify(payload)
        });
        
        if (!response.ok) {
            throw new Error(`ERP API 请求失败，状态码: ${response.status}`);
        }
        
        const result = await response.json();
        
        // 处理AI回复 - 只有在同步消息时获取到ai_reply才主动弹出AI回复提醒
        if (result.ChatRemind && result.ChatRemind.success && result.ChatRemind.content && result.ChatRemind.content.indexOf('{') > 0) {
            // 如果不是当前对话，则不要显示
            const currentChatId = getCurrentChatId();
            if (payload.chat_serialized !== currentChatId) {
                console.log('不是当前对话，不显示AI回复');
                // 关闭已经显示的窗口
                const event = new CustomEvent('ai-reply-alert-close');
                window.dispatchEvent(event);
            } else {
                console.log('同步消息时获取到AI回复，主动弹出提醒');
                const structuredData = parseResponse(result.ChatRemind.content);
                if (structuredData && result.ChatRemind.success) {
                    // 触发AI回复事件
                    console.log('messagesync 333 AI回复数据, 弹窗:', structuredData);
                    const event = new CustomEvent('ai-reply-alert', {
                        detail: { 
                            data: structuredData,
                            chatId: payload.chat_serialized,
                            nickname: payload.nickname
                        }
                    });
                    window.dispatchEvent(event);
                }
            }
        }
        
        // 显示成功提示
        showSyncSuccessToast(payload.messages.length);
        
        return true;
    } catch (error) {
        console.error('发送消息到 ERP 时出错:', error);
        return false;
    }
}

/**
 * 获取头像图片
 * @returns 头像URL
 */
function getHeaderImage(): string {
    const imgElement = document.querySelector('#main header img');
    return imgElement ? imgElement.getAttribute('src') || '' : '';
}

/**
 * 解析AI回复
 * @param aiReply AI回复字符串
 * @returns 解析后的数据
 */
function parseResponse(aiReply: string): any {
    try {
        // 移除可能存在的 HTML 标签
        let cleanedText = aiReply;
        
        // 移除开头的 HTML 标签，如 <p><code>json
        cleanedText = cleanedText.replace(/<p>.*?<code>.*?(\{)/s, '$1');
        
        // 移除结尾的 HTML 标签，如 </code></p>
        cleanedText = cleanedText.replace(/(\})\s*<\/code>.*?<\/p>\s*$/s, '$1');
        
        // 查找 JSON 开始的位置
        const jsonStartIndex = cleanedText.indexOf('{');
        if (jsonStartIndex >= 0) {
            const jsonPart = cleanedText.substring(jsonStartIndex);
            // 查找 JSON 结束的位置（最后一个 }）
            const lastBraceIndex = jsonPart.lastIndexOf('}');
            if (lastBraceIndex >= 0) {
                const cleanJsonPart = jsonPart.substring(0, lastBraceIndex + 1);
                return JSON.parse(cleanJsonPart);
            }
            return JSON.parse(jsonPart);
        }
        return null;
    } catch (error) {
        console.error('解析AI回复出错:', error);
        return null;
    }
}

/**
 * 显示同步成功提示
 * @param messageCount 消息数量
 */
function showSyncSuccessToast(messageCount: number): void {
    // 创建提示元素
    const toast = document.createElement('div');
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        background: rgba(0, 0, 0, 0.7);
        color: white;
        padding: 10px 20px;
        border-radius: 4px;
        z-index: 9999;
        animation: fadeInOut 2s ease-in-out forwards;
    `;
    toast.textContent = `同步${messageCount}条信息成功`;
    document.body.appendChild(toast);

    // 2秒后自动移除提示
    setTimeout(() => {
        toast.remove();
    }, 2000);

    // 添加动画样式
    if (!document.querySelector('#sync-toast-style')) {
        const style = document.createElement('style');
        style.id = 'sync-toast-style';
        style.textContent = `
            @keyframes fadeInOut {
                0% { opacity: 0; }
                20% { opacity: 1; }
                80% { opacity: 1; }
                100% { opacity: 0; }
            }
        `;
        document.head.appendChild(style);
    }
}

/**
 * 获取并缓存当前聊天消息
 * @returns 消息数据或null
 */
export async function fetchAndCacheCurrentChatMessages(): Promise<MessageData[] | null> {
    const chatId = getCurrentChatId();
    if (!chatId) {
        console.warn('无法获取对话 ID');
        return null;
    }

    // 检查是否已经在同步中
    if (syncingChats.has(chatId)) {
        console.log(`对话 ${chatId} 正在同步中，跳过重复请求`);
        return null;
    }

    // 检查是否在冷却时间内
    const now = Date.now();
    const lastSync = lastSyncTimestamps[chatId] || 0;
    if (now - lastSync < SYNC_COOLDOWN) {
        console.log(`对话 ${chatId} 在冷却时间内，跳过同步 (${Math.round((now - lastSync) / 1000)}秒 < ${SYNC_COOLDOWN / 1000}秒)`);
        return null;
    }

    try {
        // 标记为正在同步
        syncingChats.add(chatId);

        const currentMessages = await fetchCurrentChatMessages();
        const currentCount = currentMessages.length;

        const storedCount = await getStoredMessageCount(chatId);

        if (currentCount !== storedCount) {
            console.log(`对话 ${chatId} 有新消息 (${storedCount} -> ${currentCount})，提交到后台`);
            
            // 更新最近同步时间戳
            lastSyncTimestamps[chatId] = now;
            
            // 更新存储的消息数量
            await updateStoredMessageCount(chatId, currentCount);
            
            // 提交消息到 ERP 后台
            const success = await sendMessagesToERP(chatId, currentMessages);
            if (success) {
                console.log(`对话 ${chatId} 的消息已成功提交到 ERP`);
            } else {
                console.warn(`对话 ${chatId} 的消息提交到 ERP 失败`);
            }
            
            return currentMessages;
        } else {
            console.log(`对话 ${chatId} 的消息数量未变化 (${storedCount} -> ${currentCount})，无需获取`);
            return null;
        }
    } finally {
        // 无论成功失败，都移除同步标记
        syncingChats.delete(chatId);
    }
}

// 创建防抖版本的fetchAndCacheCurrentChatMessages函数
export const debouncedFetchAndCacheCurrentChatMessages = debounce(fetchAndCacheCurrentChatMessages, 1000); 